package com.x.bff.app.factory.social;

import com.x.bff.app.factory.cms.ContentFactory;
import com.x.bff.app.factory.customer.CustomerFactory;
import com.x.bff.app.model.vo.cms.ContentVO;
import com.x.bff.app.model.vo.customer.CustomerVO;
import com.x.bff.app.model.vo.social.CustomerSlideListVO;
import com.x.core.web.page.PageDomain;
import com.x.provider.api.common.enums.ItemTypeEnum;
import com.x.provider.api.general.enums.CmsOptions;
import com.x.provider.api.general.model.dto.cms.ContentDTO;
import com.x.provider.api.general.model.dto.cms.ContentMyReqDTO;
import com.x.provider.api.general.service.CmsRpcService;
import com.x.redis.domain.LongTypeTuple;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SocialFactoryImpl implements SocialFactory{

    private final CustomerFactory customerFactory;
    private final ContentFactory contentFactory;
    private final CmsRpcService cmsRpcService;

    public SocialFactoryImpl(CustomerFactory customerFactory,
                             ContentFactory contentFactory,
                             CmsRpcService cmsRpcService){
        this.customerFactory = customerFactory;
        this.contentFactory = contentFactory;
        this.cmsRpcService = cmsRpcService;
    }

    @Override
    public List<CustomerSlideListVO> prepare(List<LongTypeTuple> slideCustomerIdList, Long sessionCustomerId) {
        Map<Long, LongTypeTuple> customerScoreMap = slideCustomerIdList.stream().collect(Collectors.toMap(item -> item.getValue(), item -> item));
        List<Long> customerIdList = slideCustomerIdList.stream().map(item -> item.getValue()).collect(Collectors.toList());
        List<CustomerVO> customerVOList = customerFactory.prepare(customerIdList, sessionCustomerId);
        List<ContentDTO> contentList = cmsRpcService.listMyContent(ContentMyReqDTO.builder().options(List.of(CmsOptions.CONTENT.name())).pageDomain(new PageDomain(0L, Integer.MAX_VALUE))
                .sessionCustomerId(sessionCustomerId).itemType(ItemTypeEnum.ALBUM.getValue()).build()).getData().getList();
        Map<Long, List<ContentVO>> contentVoMap = contentFactory.prepare(contentList).stream().collect(Collectors.groupingBy(item -> item.getCustomerId()));
        List<CustomerSlideListVO> result = new ArrayList<>();
        customerVOList.stream().forEach(item -> {
            CustomerSlideListVO customerSlideListVO = new CustomerSlideListVO();
            customerSlideListVO.setCustomer(item);
            customerSlideListVO.setCursor(customerScoreMap.get(item.getId()).getScore().longValue());
            customerSlideListVO.setCustomerContentList(contentVoMap.get(item.getId()));
            result.add(customerSlideListVO);
        });
        return result;
    }
}
